#--*--coding=utf-8--*--
#MaterialCodeGenerator8.py
#

import chardet

import sys
import json
import sqlite3
from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QComboBox, QLineEdit, QPushButton, QLabel, QMessageBox)
from PySide6.QtCore import Qt

class CodeGenerator(QWidget):
    def __init__(self):
        super().__init__()
        
        self.initUI()
        self.load_rules_from_json()
        self.init_db()
    
    def initUI(self):
        self.layout = QVBoxLayout()

        self.groups_layout = QHBoxLayout()
        self.layout.addLayout(self.groups_layout)

        self.add_group_button = QPushButton("Add Group")
        self.remove_group_button = QPushButton("Remove Group")
        self.generate_code_button = QPushButton("Generate Code")
        self.copy_code_button = QPushButton("Copy Code")

        self.add_group_button.clicked.connect(self.add_group)
        self.remove_group_button.clicked.connect(self.remove_group)
        self.generate_code_button.clicked.connect(self.generate_code)
        self.copy_code_button.clicked.connect(self.copy_code)

        self.layout.addWidget(self.add_group_button)
        self.layout.addWidget(self.remove_group_button)
        self.layout.addWidget(self.generate_code_button)
        self.layout.addWidget(self.copy_code_button)

        self.code_label = QLabel("Generated Code: ")
        self.layout.addWidget(self.code_label)

        self.setLayout(self.layout)
        self.setWindowTitle('Material Code Generator')

    def load_rules_from_json(self):
        with open('rules4.json', 'r') as f:
            self.rules = json.load(f)

    def init_db(self):
        self.conn = sqlite3.connect('codes.db')
        self.cursor = self.conn.cursor()
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS codes (code TEXT UNIQUE)''')
        self.conn.commit()

    def add_group(self):
        group_index = len(self.groups_layout.children()) // 2  # Each group has a combo and a line edit
        group_data = self.rules['groups'][group_index] if group_index < len(self.rules['groups']) else {'name': f'Category {group_index + 1}', 'options': []}
        
        layout = QHBoxLayout()
        combo = QComboBox(self)
        for option in group_data['options']:
            combo.addItem(option)
        combo.setEditable(True)
        combo.setInsertPolicy(QComboBox.NoInsert)
        combo.completer().setCompletionMode(QComboBox.PopupCompletion)
        combo.currentTextChanged.connect(self.update_code)

        search_box = QLineEdit(self)
        search_box.textChanged.connect(lambda text, c=combo: self.search(text, c))

        layout.addWidget(combo)
        layout.addWidget(search_box)
        self.groups_layout.addLayout(layout)

    def remove_group(self):
        if self.groups_layout.count() > 0:
            self.groups_layout.takeAt(self.groups_layout.count() - 1).deleteLater()

    def update_code(self, text=None):
        code_parts = []
        for i in range(self.groups_layout.count()):
            layout = self.groups_layout.itemAt(i).layout()
            combo = layout.itemAt(0).widget()
            code_parts.append(combo.currentText())
        self.generated_code = '.'.join(code_parts)
        self.code_label.setText(f"Generated Code: {self.generated_code}")

    def generate_code(self):
        self.update_code()
        if self.is_code_unique():
            self.show_code_confirmation()
        else:
            QMessageBox.warning(self, "Warning", "The generated code already exists in the database.")

    def is_code_unique(self):
        self.cursor.execute("SELECT * FROM codes WHERE code=?", (self.generated_code,))
        return self.cursor.fetchone() is None

    def show_code_confirmation(self):
        msg_box = QMessageBox()
        msg_box.setIcon(QMessageBox.Information)
        msg_box.setText(f"Generated Code: {self.generated_code}")
        msg_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msg_box.buttonClicked.connect(self.save_code_to_db)
        msg_box.exec_()

    def save_code_to_db(self, button):
        if button.text() == "OK":
            try:
                self.cursor.execute("INSERT INTO codes (code) VALUES (?)", (self.generated_code,))
                self.conn.commit()
            except sqlite3.IntegrityError:
                QMessageBox.warning(self, "Warning", "The generated code already exists in the database.")
    
    def copy_code(self):
        clipboard = QApplication.clipboard()
        clipboard.setText(self.generated_code)
        QMessageBox.information(self, "Success", "Code copied to clipboard!")

    def search(self, text, combo):
        model = combo.model()
        items = [model.index(i, 0).data() for i in range(model.rowCount())]
        filtered_items = [item for item in items if text.lower() in item.lower()]
        combo.clear()
        combo.addItems(filtered_items)
        if filtered_items:
            combo.setCurrentIndex(0)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = CodeGenerator()
    ex.show()
    sys.exit(app.exec())